//
//  JMBuyHelper.m
//  eBooks
//
//  Created by JunMing on 2020/1/20.
//  Copyright © 2020 赵俊明. All rights reserved.
//

#import "JMBuyHelper.h"
#import <StoreKit/StoreKit.h>
@interface JMBuyHelper()<SKPaymentTransactionObserver, SKProductsRequestDelegate>
- (void)requestProUpgradeProductData;
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions;
- (void)PurchasedTransaction: (SKPaymentTransaction *)transaction;
- (void)completeTransaction: (SKPaymentTransaction *)transaction;
- (void)failedTransaction: (SKPaymentTransaction *)transaction;
- (void)paymentQueueRestoreCompletedTransactionsFinished: (SKPaymentTransaction *)transaction;
- (void)paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error;
- (void)restoreTransaction:(SKPaymentTransaction *)transaction;
- (void)provideContent:(NSString *)product;
- (void)recordTransaction:(NSString *)product;
@end

@implementation JMBuyHelper

// MARK:-- **************** 点击购买
- (void)startBuy:(notifyBlock)notifBlock {
    self.notify = notifBlock;
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        if ([SKPaymentQueue canMakePayments]) {
            [self requestProductData:@"new.epubReader.eBooks"];
        }else{
            self.notify(@{@"status":@"0",@"msg":@"您的手机没有打开程序内付费购买"});
        }
    });
}
    
// MARK:-- **************** 恢复购买
- (void)buy_restore {
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
    
// MARK:-- 内购项目
// 去苹果服务器请求产品信息
- (void)requestProductData:(NSString *)productId {
    NSArray *productArr = [[NSArray alloc]initWithObjects:productId, nil];
    NSSet *productSet = [NSSet setWithArray:productArr];
    SKProductsRequest *request = [[SKProductsRequest alloc]initWithProductIdentifiers:productSet];
    request.delegate = self;
    [request start];
}
    
// MARK:-- SKProductsRequestDelegate
// 收到的产品信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    // 发送内购请求
    NSArray *myProduct = response.products;
    SKPayment *payment = [SKPayment paymentWithProduct:myProduct.firstObject];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

// MARK:-- SKRequestDelegate
// 弹出错误信息
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.notify(@{@"status":@"0",@"msg":[error localizedDescription]});
    });
}
    
- (void)requestDidFinish:(SKRequest *)request {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"----------反馈信息结束--------------");
    });
}
    
// SKPaymentTransactionObserver 千万不要忘记绑定，代码如下：
// ----监听购买结果
// [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
- (void)PurchasedTransaction:(SKPaymentTransaction *)transaction {
    // NSLog(@"-----PurchasedTransaction----");
    NSArray *transactions =[[NSArray alloc] initWithObjects:transaction, nil];
    [self paymentQueue:[SKPaymentQueue defaultQueue] updatedTransactions:transactions];
}
//交易结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
    // NSLog(@"-----paymentQueue--------");
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState){
            case SKPaymentTransactionStatePurchased:
            [self completeTransaction:transaction];
            break;
            case SKPaymentTransactionStateFailed:
            [self failedTransaction:transaction];
            break;
            case SKPaymentTransactionStateRestored:
            [self restoreTransaction:transaction];
            break;
            case SKPaymentTransactionStatePurchasing:
            // NSLog(@"-----商品添加进列表 --------");
            break;
            default:
            break;
        }
    }
}
    
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    // NSLog(@"-----completeTransaction--------");
    NSString *product = transaction.payment.productIdentifier;
    if ([product length] > 0) {
        NSArray *tt = [product componentsSeparatedByString:@"."];
        NSString *bookid = [tt lastObject];
        if ([bookid length] > 0) {
            [self recordTransaction:bookid];
            [self provideContent:bookid];
        }
    }
    // Remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
    
// 购买成功, 记录交易
- (void)recordTransaction:(NSString *)product {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"superUser"];
    self.notify(@{@"status":@"1",@"msg":@"已经购买过啦😊"});
}
    
// 处理下载内容
- (void)provideContent:(NSString *)product {}
    
// 已经购买过该商品
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"superUser"];
    self.notify(@{@"status":@"1",@"msg":@"已经购买过啦😊"});
}
    
// 购买失败, 交易失败
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    self.notify(@{@"status":@"0",@"msg":@"购买失败,请重试！"});
}
    
// 不知道干啥用的还
// MARK:-- connection delegate
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentTransaction *)transaction {}
- (void)paymentQueue:(SKPaymentQueue *) paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error {}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {}
- (void)dealloc {
    //解除监听
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)fadeback_copyright {
    // self.router(@{@"type":@"url",@"url":@"http://www.restcy.com/2018/07/yinsizhengce/"});
    NSMutableString *mailUrl = [[NSMutableString alloc] init];
    
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"tonyzhao60@gmail.com"];
    [mailUrl appendFormat:@"mailto:%@", [toRecipients componentsJoinedByString:@","]];
    
    //添加抄送
    NSArray *ccRecipients = [NSArray arrayWithObjects:@"tonyzhao60@gmail.com", nil];
    [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];
    
    //添加密送
    NSArray *bccRecipients = [NSArray arrayWithObjects:@"tonyzhao60@gmail.com", nil];
    [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];
    
    // 添加主题
    [mailUrl appendString:@"&subject=反馈版权问题"];
    
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
    NSString *sysVersion= [[UIDevice currentDevice] systemVersion];
    NSString *device = [[UIDevice currentDevice] model];
    NSString *buildID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString *appVersionID = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    
    NSString *emailString = [NSString stringWithFormat:@"&body=<b>应用名称: %@, 设备类型: %@, 系统版本: %@, Build版本: %@, App版本: %@</b>", appName, device, sysVersion, buildID, appVersionID];
    [mailUrl appendString:emailString];
    
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet;
    NSString *email = [mailUrl stringByAddingPercentEncodingWithAllowedCharacters:set];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}
@end
